import Book.BookList;
import user.AdminUser;
import user.NormalUser;
import user.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LibraryManagementGUI extends JFrame {
    private BookList bookList;
    private User user;

    public LibraryManagementGUI() {
        // 初始化图书列表
        bookList = new BookList();
        // 模拟用户登录
        user = login();

        // 设置窗口基本属性
        setTitle("图书管理系统");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板并设置布局
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 1));

        // 根据用户类型添加不同的操作按钮
        String[] buttonLabels = getButtonLabels();
        for (String label : buttonLabels) {
            JButton button = new JButton(label);
            button.addActionListener(new ButtonClickListener());
            panel.add(button);
        }

        // 将面板添加到窗口中
        add(panel);
    }

    // 根据用户类型返回对应的操作按钮标签数组
    private String[] getButtonLabels() {
        if (user instanceof AdminUser) {
            return new String[]{"退出图书系统", "查找图书", "新增图书", "删除图书", "展示图书"};
        } else if (user instanceof NormalUser) {
            return new String[]{"退出图书系统", "查找图书", "借阅图书", "归还图书", "展示图书"};
        }
        return new String[]{};
    }

    // 模拟用户登录过程
    private User login() {
        String username = JOptionPane.showInputDialog("请输入你的姓名：");
        JOptionPane.showMessageDialog(null, "欢迎" + username + "来到图书管理系统");
        String[] options = {"管理员", "普通用户"};
        int choice = JOptionPane.showOptionDialog(null, "请输入你的身份：", "选择身份",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (choice == 0) {
            return new AdminUser(username);
        } else if (choice == 1) {
            return new NormalUser(username);
        }
        return null;
    }

    // 按钮点击事件监听器类
    private class ButtonClickListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String label = source.getText();
            int choice = getChoiceFromLabel(label);
            user.doOperations(choice, bookList);
        }

        // 根据按钮标签获取对应的操作编号
        private int getChoiceFromLabel(String label) {
            String[] labels = getButtonLabels();
            for (int i = 0; i < labels.length; i++) {
                if (labels[i].equals(label)) {
                    return i;
                }
            }
            return -1;
        }
    }

    public static void main(String[] args) {
        // 在事件调度线程中创建并显示窗口
        SwingUtilities.invokeLater(() -> {
            LibraryManagementGUI gui = new LibraryManagementGUI();
            gui.setVisible(true);
        });
    }
}